package com.jmda.platform.plugs.selector.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.jmda.platform.commom.HttpRequestParamParser;
import com.jmda.platform.commom.SpringContextUtil;
import com.jmda.platform.plugs.selector.event.SelectorDatasFormatEvent;
import com.jmda.platform.plugs.selector.model.SelectorConditionPo;
import com.jmda.platform.plugs.selector.model.SelectorPo;
import com.jmda.platform.plugs.selector.service.SelectorByMyBatisServiceImpl;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

@Controller
@RequestMapping("/selectorController")
public class SelectorControlle {

	@Resource
	SelectorByMyBatisServiceImpl selectorByMyBatisService;

	@RequestMapping("/getPage")
	public String getPage(String id, HttpServletRequest request, ModelMap map) throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> paramsMap = HttpRequestParamParser.formatParam(request);
		XStream xstream = new XStream(new DomDriver("utf-8"));
		xstream.processAnnotations(SelectorPo.class);
		StringBuffer datasparams = new StringBuffer();
		String[] idArray = id.split("\\|");
		String realPath = getFilePath(idArray.length > 1 ? idArray[0] : id);
		if (realPath != null && realPath.trim().length() > 0) {
			InputStream input = this.getClass().getResourceAsStream(realPath);
			SelectorPo dictionaryModel = (SelectorPo) xstream.fromXML(input);
			List<SelectorConditionPo> conditons = dictionaryModel.getConditions();
			for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				if (!key.equals("id")) {
					datasparams.append("&").append(key).append("=").append(value);
					paramsMap.put(key, value);
				}
			}
			map.put("isOpenCondition", dictionaryModel.getIsOpenCondition());
			map.put("hasWestTable", dictionaryModel.getHasWestTable());
			map.put("actionValue", dictionaryModel.getActionValue());
			map.put("title", dictionaryModel.getTitle());
			map.put("id", idArray.length > 1 ? idArray[0] : id + datasparams.toString());
			// modify by wangwq 如果通过URL传递多选则执行多选
			map.put("multiple", idArray.length > 1 && idArray[1].equals("multiple") ? true : dictionaryModel.getMultiple());
			map.put("sql", dictionaryModel.getSql());
			map.put("fields", dictionaryModel.getFidlds());
			map.put("conditions", conditons);
			map.put("fitColumns", dictionaryModel.getFitColumns());
			map.put("paramsMap", paramsMap);
		}
		return "plugs/selector";
	}

	@RequestMapping("/queryOne")
	@ResponseBody
	public String queryOne(String id, HttpServletRequest request) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		XStream xstream = new XStream(new DomDriver("utf-8"));
		xstream.processAnnotations(SelectorPo.class);
		Map<String, Object> json = new HashMap<String, Object>();
		String[] idArray = id.split("\\|");
		String realPath = getFilePath(idArray.length > 1 ? idArray[0] : id);
		if (realPath != null && realPath.trim().length() > 0) {
			Map<String, Object> paramsMap = HttpRequestParamParser.formatParam(request);
			InputStream input = this.getClass().getResourceAsStream(realPath);
			SelectorPo dictionaryModel = (SelectorPo) xstream.fromXML(input);
			List<Map<String, Object>> list = Lists.newArrayList();
			list = selectorByMyBatisService.queryDatas(dictionaryModel, 0, 10, paramsMap);
			if (list.size() == 1) {
				list = formatDatas(id, dictionaryModel, paramsMap, list);
				json.put("rs", 1);
				json.put("datas", list.get(0));
			} else if (list.size() > 1) {
				json.put("rs", 2);
			} else {
				json.put("rs", 0);
			}
		} else {
			json.put("rs", -1);
		}
		return mapper.writeValueAsString(json);
	}

	@RequestMapping("/getDatas")
	@ResponseBody
	public String getDictionaryDatas(String id, HttpServletRequest request) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> paramsMap = HttpRequestParamParser.formatParam(request);
		int page = NumberUtils.toInt((String) paramsMap.get("page"), 0);
		if (page >= 1) {
			page = page - 1;
		}
		int pageSize = NumberUtils.toInt((String) paramsMap.get("rows"), 10);
		XStream xstream = new XStream(new DomDriver("utf-8"));
		xstream.processAnnotations(SelectorPo.class);
		Map<String, Object> json = new HashMap<String, Object>();
		String realPath = getFilePath(id);
		if (realPath != null && realPath.trim().length() > 0) {

			InputStream input = this.getClass().getResourceAsStream(realPath);
			SelectorPo dictionaryModel = (SelectorPo) xstream.fromXML(input);
			List<Map<String, Object>> list = Lists.newArrayList();
			int total = 0;
			list = selectorByMyBatisService.queryDatas(dictionaryModel, page, pageSize, paramsMap);
			total = selectorByMyBatisService.queryDatasTotal(dictionaryModel, paramsMap);

			if (list != null && list.size() > 0) {
				json.put("total", total);
				json.put("rows", formatDatas(id, dictionaryModel, paramsMap, list));
			} else {
				return "[]";
			}
		} else {
			return "[]";
		}

		return mapper.writeValueAsString(json);
	}

	public String getFilePath(String id) {
		return "/selector/" + id;
	}

	public List<Map<String, Object>> formatDatas(String id, SelectorPo dictionaryModel, Map<String, Object> params, List<Map<String, Object>> datas) {
		if (dictionaryModel.getEventClass() != null && dictionaryModel.getEventClass().trim().length() > 0) {
			try {
				Class<SelectorDatasFormatEvent> eventClass = (Class<SelectorDatasFormatEvent>) Class.forName(dictionaryModel.getEventClass());
				SelectorDatasFormatEvent event = SpringContextUtil.getBean(eventClass);
				if (event != null) {
					return event.format(id, params, datas);
				}
			} catch (ClassNotFoundException e) {
				System.out.println("ClassNotFoundException");
			}
		}
		return datas;
	}
}
